package com.yang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.domain.Bill;
import com.yang.domain.Category;
import com.yang.mapper.BillMapper;
import com.yang.mapper.CategoryMapper;
import com.yang.service.CategoryService;
import com.yang.utils.ThreadLocalUtil;
import com.yang.vo.MonthStatisticVo;
import com.yang.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private BillMapper billMapper;

    @Override
    public ResponseResult getMonthStatistic(Long categoryId, Integer month) {
        //1.获取用户id
        Long userId = Long.valueOf(ThreadLocalUtil.get().toString());

        //2.构建查询条件
        LambdaQueryWrapper<Bill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bill::getCategoryId,categoryId);
        queryWrapper.eq(Bill::getUserId,userId);

        //3.筛选数据
        List<Bill> bills = billMapper.selectList(queryWrapper).stream().filter(
                bill -> {
                    LocalDateTime billDate = bill.getDate();
                    if (billDate == null)
                        return false;
                    return billDate.getMonth().getValue() == month;
                }
        ).collect(Collectors.toList());

        //4.计算数据
        Float totalIncome=0f;
        Float totalExpenditure=0f;

        for (Bill bill : bills) {
            if (bill.getIncome()!=null){
                totalIncome+=bill.getIncome();
            }
            if (bill.getExpenditure()!=null){
                totalExpenditure+=bill.getExpenditure();
            }
        }

        MonthStatisticVo monthStatisticVo = MonthStatisticVo.builder()
                .monthIncome(totalIncome)
                .monthExpenditure(totalExpenditure)
                .build();

        //5.返回数据
        return ResponseResult.success(monthStatisticVo);
    }
}
